package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var addr = flag.String("addr", "localhost:8080", "http service address")

var upgrader = websocket.Upgrader{}

func echo(w http.ResponseWriter, r *http.Request) {
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()
		if err != nil {
			if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
				log.Println("Client requested shutdown")
			} else {
				log.Println("read:", err)
			}
			break // Break the loop when read fails
		}
		log.Printf("recv: %s\n", message)
		echoMsg := fmt.Sprintf("Response from server: %s", message)
		err = c.WriteMessage(mt, []byte(echoMsg))
		if err != nil {
			log.Println("write:", err)
			break // Break the loop when write fails
		}
	}
}

func main() {
	flag.Parse()
	log.SetFlags(0)
	http.HandleFunc("/echo", echo)
	log.Fatal(http.ListenAndServe(*addr, nil))
}
